#include "proto_mbus.h"
#include "discovery_meter.h"
#include <string.h>
#include <stdint.h>
#include "utils.h"
/*
搜表流程：
1、创建搜表事件discover_meter_event  discover_meter;
2、调用discovery_start(&discover_meter，10);设置搜索数目，启动搜表
3、discovery_meter_proto_handler()中通过协议解析，判断单次搜表结果：无、单个、冲突
4、discovery_meter_hook_10ms()中根据单次搜表结果，调用discovery_meter_handler()遍历二叉树
*/
#define SINGLE    ( 1 )
#define NONE      (-1 )
#define COLLIDE   (-2 )
#define WAIT      (-3 )  
#define WAIT_TIME (80)//发送搜表报文间隔时间  单位10ms
#define MASS_TIME (26)//MBUS总线杂波等待时间  单位10ms
#define MSS_DATA_NUMS (10)

static discover_meter_event discover_meter = 
{
	.status = SEARCH_END,                
	.res = SEARCH_NONE,                 
	.meter_nums = 0,
	.found_nums = 0,
};

static void send_search_frame(uint8_t wildcard[])
{
		
}
static int  discovery_meter_proto_handler(uint8_t wildcard[])
{    
	   static uint32_t timer_tick = 0;
	   
	   if(timer_tick ==0)
		 {
			 send_search_frame(wildcard);//根据wildcard 发送搜表报文
			 timer_tick = WAIT_TIME;
			 return WAIT;
		 }
		 else
		 {
			 timer_tick--;
			 if(timer_tick > (WAIT_TIME -MASS_TIME))
			 {
				 //这段时间MBUS总线有乱码，需要清空内存池，防止对搜表逻辑造成误判
			 } 
			 if(timer_tick == 0)
			 {
				 int idx,peek_len;
				 //idx = get_smart_frame();//此时等待时间到  解析收到的数据S
				 if(idx >=0)//合法报文，找到一只表
				 {
					 return SINGLE;
				 }
				 else
				 {
					   if(peek_len >MSS_DATA_NUMS)//非法报文，数据超过10个 认为冲突
							 return COLLIDE;
						 else//非法报文 数据少于10个  认为无设备
							 return NONE;
				 }
			 }
			 else
			 {
				 return WAIT;
			 }
	
		 }
     return WAIT;
}

void  discovery_meter_hook_10ms()
{
		 uint8_t wildcard_bak[DISCOVERY_MAX_LAYER];
	   
	   if(!discovery_is_searching(&discover_meter))
			  return;
	
#if DISCOVERY_ORDER
		reverse(wildcard_bak,DISCOVERY_MAX_LAYER);
#endif	
		 
		int res = discovery_meter_proto_handler(wildcard_bak);

		switch(res)
		{
			case NONE:
			 discovery_get_none_meter(&discover_meter);
			 break;
			case SINGLE:
			 discovery_get_one_meter(&discover_meter);
			 break;
			case COLLIDE:
				discovery_meters_collide(&discover_meter);
				break;
			case WAIT:
			default :
				return;
		}
		discovery_meter_get_next_wildcard(&discover_meter,wildcard_bak);//遍历二叉树
	  if(!discovery_is_searching(&discover_meter))
		{
			//搜表结束
			return;
		}
}
